package Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * @author 李某
 * * @date 2021/11/19
 * *物有本末，事有终始。知其先后者，则近道矣！
 * *荷花开满池塘的前一天还是半塘荷花半塘云。
 */
public class ServletHttpResponse {
}

//导入必需的 java 库

@WebServlet("/DisplayHeader")

//扩展 HttpServlet 类
class DisplayHeader extends HttpServlet {

    // 处理 GET 方法请求的方法
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "HTTP Header 请求实例 - 菜鸟教程实例";
        String docType =
                "<!DOCTYPE html> \n";
        out.println(docType +
                "<html>\n" +
                "<head><meta charset=\"utf-8\"><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<table width=\"100%\" border=\"1\" align=\"center\">\n" +
                "<tr bgcolor=\"#949494\">\n" +
                "<th>Header 名称</th><th>Header 值</th>\n" +
                "</tr>\n");

        Enumeration headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String paramName = (String) headerNames.nextElement();
            out.print("<tr><td>" + paramName + "</td>\n");
            String paramValue = request.getHeader(paramName);
            out.println("<td> " + paramValue + "</td></tr>\n");
        }
        out.println("</table>\n</body></html>");
    }

    // 处理 POST 方法请求的方法
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
// 配套XMl配置
/**
 * <?xml version="1.0" encoding="UTF-8"?>
 * <web-app>
 *   <servlet>
 *     <!-- 类名 -->
 *     <servlet-name>DisplayHeader</servlet-name>
 *     <!-- 所在的包 -->
 *     <servlet-class>com.runoob.test.DisplayHeader</servlet-class>
 *   </servlet>
 *   <servlet-mapping>
 *     <servlet-name>DisplayHeader</servlet-name>
 *     <!-- 访问的网址 -->
 *     <url-pattern>/TomcatTest/DisplayHeader</url-pattern>
 *   </servlet-mapping>
 * </web-app>
 */


